<template>
  <LoginHeader>联合登录</LoginHeader>
  <div class="loading" v-if="isBind">登录中....</div>
  <section class="container" v-else>
    <nav class="tab">
      <a
        @click="hasAccount = true"
        :class="{ active: hasAccount }"
        href="javascript:;"
      >
        <i class="iconfont icon-bind" />
        <span>已有小兔鲜账号，请绑定手机</span>
      </a>
      <a
        @click="hasAccount = false"
        :class="{ active: !hasAccount }"
        href="javascript:;"
      >
        <i class="iconfont icon-edit" />
        <span>没有小兔鲜账号，请完善资料</span>
      </a>
    </nav>
    <div class="tab-content" v-if="hasAccount">
      <CallbackBind :unionId="unionId" />
    </div>
    <div class="tab-content" v-else>
      <CallbackPatch :unionId="unionId" />
    </div>
  </section>
  <LoginFooter />
</template>

<script>
import { ref } from 'vue'
import LoginHeader from './components/login-header.vue'
import LoginFooter from './components/login-footer.vue'
import CallbackBind from './components/callback-bind.vue'
import CallbackPatch from './components/callback-patch.vue'
import { useQQLogin } from '@/api/user'
import router from '@/router'
import store from '@/store'
import Message from '@/components/library/Message'
export default {
  name: 'PageCallback',
  components: { LoginHeader, LoginFooter, CallbackBind, CallbackPatch },
  setup() {
    const hasAccount = ref(true)
    const unionId = ref(null)
    // 假设已经绑定，默认会去做一次登录，如果登录失败证明未绑定。
    const isBind = ref(true)
    // 判断QQ是否登录
    if (QC.Login.check()) {
      // 登录后获取 QQ 唯一标识
      QC.Login.getMe((openId, accessToken) => {
        // console.log(openId, accessToken)
        unionId.value = openId
        // 将QQ唯一标识发送给后台去查询有无绑定
        useQQLogin(openId)
          .then((data) => {
            // 登录成功拿到用户信息，跳转首页
            store.commit('user/setUser', data.result)
            // 合并购物车操作
            store.dispatch('cart/mergeLocalCart')
            router.push(store.state.user.redirectUrl)
            Message({ msg: 'QQ登陆成功' })
          })
          .catch((e) => {
            // 登录失败，没有绑定小兔鲜账号
            isBind.value = false
          })
      })
    }
    return { hasAccount, isBind, unionId }
  },
}
</script>

<style scoped lang="less">
.container {
  padding: 25px 0;
}
.loading {
  margin: 25px auto;
  width: 1240px;
  height: 730px;
  background-color: red;
}
.tab {
  background: #fff;
  height: 80px;
  padding-top: 40px;
  font-size: 18px;
  text-align: center;
  a {
    color: #666;
    display: inline-block;
    width: 350px;
    line-height: 40px;
    border-bottom: 2px solid #e4e4e4;
    i {
      font-size: 22px;
      vertical-align: middle;
    }
    span {
      vertical-align: middle;
      margin-left: 4px;
    }
    &.active {
      color: @xtxColor;
      border-color: @xtxColor;
    }
  }
}
.tab-content {
  min-height: 600px;
  background: #fff;
}
</style>
